/**
 * 清除字符串两端指定字符
 * @param {*} str 
 * @param {*} char 
 * @param {*} type 
 * @returns 
 */
const dmStrTrim = (str, char, type) => {
  if (!str) {
    return '';
  }
  if (char) {
    if (type == 'left') {
      return str.replace(new RegExp('^\\' + char + '+', 'g'), '');
    } else if (type == 'right') {
      return str.replace(new RegExp('\\' + char + '+$', 'g'), '');
    }
    return str.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
  }
  return str.replace(/^\s+|\s+$/g, '');
}

/**
 * 生成随机字符串
 * @param {*} leng 
 * @param {*} st 
 * @returns 
 */
const dmRandomStr = (leng, st) => {
  var len = leng || 32
  var str = st || '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var result = '';
  for (var i = len; i > 0; --i) {
    result += str[Math.floor(Math.random() * str.length)];
  }
  return result;
}



/**
 * 测试某个字符是属于哪一类
 * @param {*} iN 
 * @returns 
 */ 
const CharMode = (iN) => {
  if (iN >= 48 && iN <= 57) //数字 
    return 1;
  if (iN >= 65 && iN <= 90) //大写字母 
    return 2;
  if (iN >= 97 && iN <= 122) //小写 
    return 4;
  else
    return 8; //特殊字符 
}

/**
 * 计算出当前密码当中一共有多少种模式 
 * @param {*} num 
 * @returns 
 */ 
const bitTotal = (num) => {
  let modes = 0;
  for (let i = 0; i < 4; i++) {
    if (num & 1) modes++;
    num >>>= 1;
  }
  return modes;
}

/**
 * 返回密码的强度级别 
 * @param {*} sPW 
 * @returns 
 */
const checkStrong = (sPW,len) => {
  if (sPW.length < len)
    return 0; //密码太短 
  let Modes = 0;
  for (let i = 0; i < sPW.length; i++) {
    //测试每一个字符的类别并统计一共有多少种模式. 
    Modes |= CharMode(sPW.charCodeAt(i));
  }
  console.log(11111111111,bitTotal(Modes))
  return bitTotal(Modes);
}

/**
 * 验证密码强度
 * 返回值 null:密码为空 0:长度不满足(默认最少六位) 1:弱 2:中 3:强
 * @param {*} pwd 
 * @param {*} len 
 * @returns 
 */
const dmPwStrength = (pwd,len = 6) => {
  if (pwd == null || pwd == '') {
    return null;
  } else {
    let S_level = checkStrong(pwd,len);
    return S_level;
  }
}


export {
  dmStrTrim,
  dmRandomStr,
  dmPwStrength
}